﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Miao.UI
{
    /// <summary>
    /// 这个类必须在基于摄像机Canvas下才可以正常运行
    /// </summary>
    public class RestrictedCenterDrag : DragAndDrop
    {
        public bool lockX;
        public bool lockY;

        [Tooltip("拖拽局限")]
        public RectTransform restrictedRect;

        public override void OnDrag(PointerEventData eventData)
        {
            base.OnDrag(eventData);
            ClampToWindow();
        }

        public void ClampToWindow()
        {
            Vector3 pos = rectTransform.localPosition;
            Vector3 minPosition = restrictedRect.rect.min - rectTransform.rect.min;   //矩形(2D)左下角坐标相对差
            Vector3 maxPosition = restrictedRect.rect.max - rectTransform.rect.max;   //矩形(2D)右上角坐标相对差
       

            pos.x = Mathf.Clamp(rectTransform.localPosition.x, lockX ? minPosition.x : restrictedRect.rect.xMin, lockX ? maxPosition.x : restrictedRect.rect.xMax);
            pos.y = Mathf.Clamp(rectTransform.localPosition.y, lockY ? minPosition.y : restrictedRect.rect.yMin, lockY ? maxPosition.y : restrictedRect.rect.yMax);
            rectTransform.localPosition = pos;//最终赋值
        }
    }
}
